package com.example.javatool.recallfile;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class FileBelongRecorder {
    /**
     * 记录指定目录下所有文件的文件名和所属人，并将结果追加保存到指定文件中。
     *
     * @param directoryPath  要记录文件信息的目录路径
     * @param outputFilePath 保存文件信息的文件路径
     * @throws IOException 当文件操作出错时抛出
     */
    public static void recordFileBelong(String directoryPath, String outputFilePath) throws IOException {
        Path directory = Paths.get(directoryPath);
        if (!Files.isDirectory(directory)) {
            throw new IllegalArgumentException(directoryPath + " 不是一个有效的目录");
        }

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath, true))) {
            Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (Files.isRegularFile(file)) {
                        String fileName = file.getFileName().toString();
                        String owner = file.getParent().getParent().getFileName().toString();
                        writer.write(fileName + " " + owner);
                        writer.newLine();
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }

    public static void main(String[] args) {
        // 指定多个目录路径
        String[] directoryPaths = {
                "D:\\email\\outlookfile\\陈珏溢\\附件"
                , "D:\\email\\outlookfile\\陈珊珊\\附件"
                , "D:\\email\\outlookfile\\林琳\\附件"
                , "D:\\email\\outlookfile\\陆敏蔚\\附件"
                , "D:\\email\\outlookfile\\孟连\\附件"
                , "D:\\email\\outlookfile\\孙可欣\\附件"
                , "D:\\email\\outlookfile\\赵志堃\\附件"
                , "D:\\email\\outlookfile\\庄丽珠\\附件"
        };
        String outputFilePath = "D:\\email\\mail_file_belong.txt";
        try {
            for (String directoryPath : directoryPaths) {
                System.out.println("执行目录：" + directoryPath);
                recordFileBelong(directoryPath, outputFilePath);
            }
            System.out.println("文件所属人信息记录完成，结果已保存到 " + outputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
